import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'bottom_sheet_view.dart';
import '../../../common/utils/action_picker/action_picker.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'loading.dart';

/// 刷新回调
typedef UpdateCallBack = void Function(dynamic imgArr);

/// 选择多张图片，并上传
class ChooseImages {

  /// 添加图片按钮名称
  String? addImg;
  /// 图片地址
  List<String>? imageList;

  int? fileType;/// 参考：UploadApi.uploadImageApi
  int? resType;/// 参考：UploadApi.uploadImageApi
  int? maxCount;/// 最大数量
  int? onceCount;/// 单次最大选择数量
  final UpdateCallBack? updateCallBack;/// 图片更新回调
  /// 已上传的图片url
  final Map<AssetEntity,String> _saveMap = {};

  ChooseImages({
    this.addImg = 'addImg',
    this.imageList,
    this.fileType = 2,
    this.resType = 1,
    this.maxCount = 9,
    this.onceCount = 3,
    this.updateCallBack,
  }) {
    imageList??=[];
    imageList?.add(addImg!);
    /// 一次选择的数量不能超过最大图片选择数量
    onceCount = min(maxCount!, onceCount!);
  }

  /// 交换两个元素的位置
  void swap(int index1, int index2) {
    if (index1 < 0 ||
        index1 >= imageList!.length ||
        index2 < 0 ||
        index2 >= imageList!.length) {
      throw Exception('Invalid index');
    }
    var temp = imageList![index1];
    imageList![index1] = imageList![index2];
    imageList![index2] = temp;
    if (updateCallBack != null) updateCallBack!(imageList!);
  }

  /// 可以轮播的图片（不包含添加图片）
  List<String> carousels() {
    List<String> list = List<String>.from(imageList!.where((element) => element != addImg));
    return list;
  }

  /// 本地已选图片
  List<AssetEntity> local() {
    List<AssetEntity> list = [];
    /// 遍历已经上传的本地图片
    for (String value in imageList!) {
      /// 添加按钮跳过
      if (value == addImg) continue;
      /// 遍历map
      for (var entry in _saveMap.entries) {
        if (entry.value == value) {
          list.add(entry.key);
          break;
        }
      }
    }
    return list;
  }

  /// 弹出选择框
  void actionShow() {
    Get.bottomSheet(
      BottomSheetView(
        items: [
          SheetItem(
            label: "拍照",
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(30),
              topRight: Radius.circular(30),
            ),
            onTap: () async {
              /// 相机权限
              var privilege = await ActionPicker.cameraPrivilege(Get.context!, isVideo: false);
              /// 没有权限
              if (!privilege.result) return;
              /// 相机拍摄
              var result = await ActionPicker.camera(
                context: Get.context!,
                enableRecording: false,
              );
              if (result == null) return;
              /// 拍照图片添加上传(标记实时拍照)
              addChoosePhotos([result], isReal: 1);
            },
          ),
          SheetItem(
            label: "从相册中选择",
            onTap: () async {
              /// 相册权限
              var privilege =
              await ActionPicker.assetsPrivilege(Get.context!);
              /// 没有去权限
              if (!privilege.result) return;
              /// 相册选取
              var result = await ActionPicker.assets(
                type: RequestType.image,
                // selected: local(),
                context: Get.context!,
                maxAssets: maxAssets(),
              );
              if (result == null) return;
              /// 相册选取图片添加上传
              addChoosePhotos(result);
            },
          ),
        ],
      ),
    );
  }

  /// 最大可选数量
  int maxAssets() {
    int count = imageList!.length;
    if (count <= maxCount! - onceCount! + 1) return onceCount!;
    return max(1,maxCount!+1-count);
  }

  /// 添加选中的
  void addChoosePhotos(List list, {int? isReal = 0}) {
    List <AssetEntity> upload = [];
    for (var item in list) {
      /// 保存上传图片
      if (item is AssetEntity) upload.add(item);
    }
    /// 执行上传
    if (upload.isNotEmpty) _getImage(upload, isReal: isReal);
  }

  /// 处理获取上传图片
  Future<void> _getImage(List<AssetEntity> list, {int? isReal = 0}) async {

    if (list.isEmpty) return;
    // 异步任务集合
    List<Future<dynamic>> futures = [];
    // 临时记录，匹配异步结果，保存本地_saveMap中
    List<AssetEntity> tempData = [];
    /// 上传所有图片之后，保存纸条
    for (final asset in list) {
      /// 本地取出
      String res = _saveMap[asset]??'';
      if (res.isEmpty) {
        /// 读取文件内容
        File? imageFile = await asset.file;
        if (imageFile != null) {
          tempData.add(asset);
          // 添加任务
          // futures.add(UploadApi.uploadImageApi(
          //   fileType: fileType!,
          //   resType: resType!,
          //   file: File(imageFile.path),
          //   isReal: isReal,
          // ));
        }
      }else {
        /// 加入数组
        if (imageList!.length < maxCount!+1) {
          imageList!.insert(imageList!.indexOf(imageList!.last), res);
        }
      }
    }

    if (futures.isNotEmpty) {
      Loading.request();
      // 处理多任务
      Future.wait(futures).then((value) {
        for (var res in value) {
          int index = value.indexOf(res);
          // 插入新数据
          imageList!.insert(imageList!.indexOf(imageList!.last), res);
          if (tempData.length > index) {
            // 保存本地记录
            _saveMap[tempData[index]]=res;
          }
        }
        /// 清除处理(是否超过九张)
        removeAtIndex();
        Loading.dismiss();
      });
    }else {
      /// 清除处理(是否超过九张)
      removeAtIndex();
    }

  }

  /// 移除
  void remove(data){
    if (data is String) {
      int index = imageList!.indexOf(data);
      if (index > - 1) removeAtIndex(index: index);
    }else {
      print('====图片移除的不是字符串====');
    }
  }

  /// 移除
  void removeAtIndex({int? index}){
    /// 删除指定位置图片
    if (index != null && index < imageList!.length) imageList!.removeAt(index);
    if (imageList!.length > maxCount!) {
      imageList!.removeLast();
    } else {
      if (!imageList!.contains(addImg)) {
        imageList!.add(addImg!);
      }
    }
    /// 更新回调
    if (updateCallBack != null) updateCallBack!(imageList!);
  }
}